import store from '@/store/index.js'


// export const baseUrl = "https://csyuanzhanht.mypv.cn" //测试
export const baseUrl = "https://yunz.solarbe.com" //正式

const defaultHeader = {
	"Authorization": uni.getStorageSync('userInfo').token,
	'content-type': 'application/json',
};

export function outlogin() {
	store.dispatch('login/Logout', uni.getStorageSync('userInfo').token || '')
		.then(res => {
			uni.$u.toast(res.msg);
			if (res.code == 0) {
				// #ifdef MP-WEIXIN || H5
				uni.reLaunch({
					url: '/pages/my/index'
				});
				// #endif

				uni.redirectTo({
					url: '/pages/my/index'
				});
			}
		})
		.catch(err => {
			console.log('退出登录失败', err);
		});
}

export const request = ({
	url = '',
	method = 'GET',
	data = {},
	header = {}
}) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中...'
		});
		uni.request({
			method: method,
			url: baseUrl + '/' + url,
			data: {
				...data,
				token: uni.getStorageSync('userInfo').token || ''
			},
			header: header || defaultHeader,
			dataType: 'json',
		}).then((response) => {
			uni.hideLoading();
			let [error, res] = response;
			// if (res.data.code == 301) {
			// 	outlogin();
			// }
			resolve(res.data);
		}).catch(error => {
			let [err, res] = error;
			reject(err)
		})
	});
}

// 图片上传接口封装
export const upLoadFile = ({
	url = '',
	event = {},
	formData = {}
}) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中...'
		});
		uni.uploadFile({
			url: baseUrl + '/' + url,
			filePath: event.file.url || event.file,
			name: 'file',
			timeout: 15000,
			// #ifdef  MP-WEIXIN
			header: {
				"Authorization": uni.getStorageSync('userInfo').token,
				// "Content-Type": "application/x-www-form-urlencoded"
				"Content-Type": "multipart/form-data"
			},
			// #endif
			formData: formData,
			success: (response) => {
				uni.hideLoading();
				let data = response.data ? JSON.parse(response.data) : response.data
				resolve(data);
			},
			fail: (error) => {
				// console.log("上传失败", err);
				reject(error)
			}
		})
	});
}